import { verifyPwd } from "@/api/room";
import { ElMessage } from "element-plus";
import { defineStore } from "pinia";
import { ref } from "vue";

export interface StudyRoom {
  roomId: string;
  roomName: string;
  description: string;
  type: string;
  openness: "public" | "friends" | "private";
  capacity: number;
  memberCount: number;
  enableCamera: boolean;
  enableMic: boolean;
  enableChat: boolean;
  enableScreenShare: boolean;
  enableNote: boolean;
  canInvite: boolean;
  creator: string;
  createTime: string;
  isActive: boolean;
  password: string;
}

export interface Participant {
  userId: string;
  username: string;
  nickname: string;
  avatar: string;
  status: "studying" | "focused" | "resting" | "offline";
  studyTime: number;
  joinedAt: string;
}

export interface ChatMessage {
  id: string;
  userId: string;
  username: string;
  content: string;
  timestamp: string;
  type: "text" | "system" | "ai";
}

export const useStudyRoomStore = defineStore(
  "studyRoom",
  () => {
    const currentRoom = ref<StudyRoom | null>(null);
    const publicRooms = ref<StudyRoom[]>([]);
    const friendsRooms = ref<StudyRoom[]>([]);
    const chatMessages = ref<ChatMessage[]>([]);
    const isInRoom = ref(false);
    const studyTimer = ref(0);
    const isStudying = ref(false);

    const joinRoom = (room: StudyRoom) => {
      if (room.openness === "private") {
        verifyPwd(room.roomId, room.password)
          .then((res) => {
            if (res.data) {
              console.log(res.data);
              currentRoom.value = room;
              isInRoom.value = true;
              chatMessages.value = [];
              ElMessage.success(`已加入房间 ${room.roomName}`);
            } else {
              ElMessage.error("密码错误");
            }
          })
          .catch((error) => {
            ElMessage.error("密码错误");
          });
      } else {
        currentRoom.value = room;
        isInRoom.value = true;
        chatMessages.value = [];
        ElMessage.success(`已加入房间 ${room.roomName}`);
      }
    };

    const leaveRoom = () => {
      currentRoom.value = null;
      isInRoom.value = false;
      chatMessages.value = [];
      stopStudyTimer();
    };
    const sendMessage = (content: string, type: "text" | "ai" = "text") => {
      if (!currentRoom.value) return;

      const message: ChatMessage = {
        id: generateId(),
        userId: "current-user-id",
        username: "current-user",
        content,
        timestamp: new Date().toISOString(),
        type,
      };

      chatMessages.value.push(message);
    };

    const startStudyTimer = () => {
      isStudying.value = true;
      const interval = setInterval(() => {
        if (isStudying.value) {
          studyTimer.value++;
        } else {
          clearInterval(interval);
        }
      }, 1000);
    };

    const stopStudyTimer = () => {
      isStudying.value = false;
    };

    const resetStudyTimer = () => {
      studyTimer.value = 0;
      isStudying.value = false;
    };

    const generateId = () => {
      return Math.random().toString(36).substr(2, 9);
    };

    return {
      currentRoom,
      publicRooms,
      friendsRooms,
      chatMessages,
      isInRoom,
      studyTimer,
      isStudying,
      joinRoom,
      leaveRoom,
      sendMessage,
      startStudyTimer,
      stopStudyTimer,
      resetStudyTimer,
    };
  },
  {
    persist: true,
  }
);
